package com.blue.integration.spring.redis;

import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blue.core.util.CompressUtil;

public class FastjsonRedisSerializer implements RedisSerializer<Object>
{
	private static SerializerFeature[] serializer = new SerializerFeature[] { SerializerFeature.WriteDateUseDateFormat,
			SerializerFeature.WriteClassName };

	private static Feature[] feature = new Feature[] {};

	private boolean compress = false; // 是否压缩

	static
	{
		ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
	}

	public FastjsonRedisSerializer()
	{
	}

	public FastjsonRedisSerializer(boolean compress)
	{
		this.compress = compress;
	}

	@Override
	public byte[] serialize(Object t) throws SerializationException
	{
		if (t == null)
			return null;

		byte[] bytes = JSON.toJSONBytes(t, serializer);
		if (compress) // 压缩
		{
			bytes = CompressUtil.zip(bytes);
		}
		return bytes;
	}

	@Override
	public Object deserialize(byte[] bytes) throws SerializationException
	{
		if (bytes == null || bytes.length == 0)
			return null;

		if (compress)
		{
			bytes = CompressUtil.unzip(bytes);
		}
		Object obj = JSON.parse(bytes, feature);
		return obj;
	}

	public boolean isCompress()
	{
		return compress;
	}

	public void setCompress(boolean compress)
	{
		this.compress = compress;
	}

}
